// packageAdvance/pages/advance-detail/advance-detail.js
const app = getApp()
import {
    openSalaryCard,
    querySalaryCard
} from '../../../utils/salary-card'
import {
    getUrgentInfo,
    getAlipaySchemeApi
} from '../../../api/app'
import {
    getadvancedetailapi
} from '../../api/advance'
import {
    anit,
    confirm,
    goApp,
    goToContract,
    getCardAge,
    reportEvent,
} from '../../../utils/util'
import {
    getPaidadvance,
} from '../../../api/get-paid.js'
import user from '../../../utils/user'
import {
    getContractList
} from '../../../api/contract.js'
import dayjs from 'dayjs'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showbottom: '',
        copyData: '',
        alipayCode: '',
        flag: false,
        showDialog: false,
        isUp: false,
        checked: true,
        id: null,
        contractList: [],
        msg: {},
        companyId: '',
        idCardFront: '',
        bankcard: '',
        isOpenSalaryCard: false,
        isEdition: false,
        isCollectOpenBankAddress: '0',
        isshowCollectOpenBankAddress: 0,
        isCollectOpenBankCity: 1,
        isCollectOpenBankName: 1
    },
    // 点击复制
    // onCopywxtap() {
    //     wx.setClipboardData({
    //         data:  this.data.copyData,
    //         success: function () {
    //             wx.getClipboardData({
    //                 success: function (res) {
    //                     console.log(res.data) // 打印赋值的数据
    //                     wx.showToast({
    //                         title: '复制成功',
    //                         icon: 'none'
    //                     })
    //                 }
    //             })
    //         }
    //     })
    // },
    onClosedialog() {
        this.setData({
            showDialog: false
        })
    },
    onClosePop() {
        this.setData({
            isUp: false
        })
    },
    onLook() {
        wx.navigateTo({
            url: '/pages/alipay-desc/alipay-desc',
        })
    },
    onOpaenDialog() {
        this.setData({
            showDialog: true
        })
    },
    async onGetBankInAlipay() {
        // if (!user.alipayAccount) {
        //     this.setData({
        //         flag: false
        //     })
        // } else {
        //     getAlipaySchemeApi({
        //         page:'package-mine/pages/salary/salary',
        //         query:'from=scheme'
        //     }).then((res)=>{
        //         console.log(res)
        //         this.setData({
        //             copyData: res,
        //             flag: true
        //         })
        //     })
        // }
        this.setData({
            flag: true,
            isUp: true
        })
    },
    // 获取个人信息
    async getUrgentInfo() {
        const result = await getUrgentInfo()
        console.log(result, 'resres')
        this.data.idCardFront = result.idCardFront
    },
    onChecked() {
        this.setData({
            checked: !this.data.checked
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        console.log(options)
        await user.waitLogin()
        this.setData({
            id: options.id,
            showbottom: options.showbottom,
            bankcard: user.bankCardNo,
            isOpenSalaryCard: user.isOpenSalaryCard,
            isCollectOpenBankCity: options.isCollectOpenBankCity,
            isCollectOpenBankName: options.isCollectOpenBankName
        })
        this.getadvancedetail()
    },
    getadvancedetail() {
        getadvancedetailapi({
            id: this.data.id
        }).then(async (res) => {
            console.log(res, 'djhfkhjdhujf')
            res.payTime = dayjs(res.payTime).format('YYYY-MM-DD hh:mm:ss')
            // 0 ：审核中 1:未通过 2:待领取 3：已领取 4：停止 5：失败(endstatus最终状态)  applyStatus初审状态 auditStatus二审状态
            if (res.applyStatus === 0 && res.auditStatus === null && res.status === null) {
                res.endstatus = 0
            } else if (res.applyStatus === 1 && res.auditStatus === null && res.status === null) {
                res.endstatus = 0
            } else if (res.applyStatus === 1 && res.auditStatus === 0 && res.status === null) {
                res.endstatus = 0
            } else if (res.applyStatus === 1 && res.auditStatus === 0 && res.status === 0) {
                res.endstatus = 0
            } else if (res.applyStatus === 1 && res.auditStatus === 1 && res.status === 1) {
                res.endstatus = 3
            } else if (res.applyStatus === 2 && res.auditStatus === null && res.status === null) {
                res.endstatus = 1
            } else if (res.applyStatus === 1 && res.auditStatus === 1 && res.status === 0) {
                res.endstatus = 2
            } else if (res.applyStatus === 1 && res.auditStatus === 1 && res.status === 2) {
                res.endstatus = 4
            } else if (res.applyStatus === 1 && res.auditStatus === 1 && res.status === 3) {
                res.endstatus = 6
            } else if (res.applyStatus === 1 && res.auditStatus === 1 && res.status === 4) {
                res.endstatus = 5
            } else if (res.applyStatus === 1 && res.auditStatus === 2 && res.status === null) {
                res.endstatus = 1
            } else if (res.applyStatus === 1 && res.auditStatus === 2 && res.status === 0) {
                res.endstatus = 1
            }
            this.setData({
                companyId: res.companyId,
                msg: res
            })
            const age = await getCardAge(res.idCardNo)
            if (res.flagQuicklyGetSalary && (age >= 45)) {
                this.setData({
                    isEdition: true
                })
            }
            const contractList = await getContractList({
                companyId: res.companyId
            })
            this.data.contractList = contractList
            if (contractList.length === 0) {
                return
            }
            this.data.hasContract = true
            console.log('第一个合同')
            app.confirm(`应劳务公司要求，需要您签署合同后领薪，您有${contractList.length}份合同待签署。`).then(() => {
                goToContract(contractList[0].flowPath, contractList[0].id)
            })
        })
    },
    async onGetBank() {
        const res = await getadvancedetailapi({
            id: this.data.id
        })
        console.log(res, this.data.contractList, 'gjidsghy')
        this.setData({
            isshowCollectOpenBankAddress: res.isCollectOpenBankAddress,
        })
        const age = await getCardAge(res.idCardNo)
        if (res.flagQuicklyGetSalary && (age >= 45)) {
            this.setData({
                isEdition: true
            })
        }
        this.setData({
            companyId: res.companyId,
        })
        let bankcardflag = !!this.data.bankcard
        let idCardFront = !!this.data.idCardFront
        console.log(this.data.msg.isNeedIdcardPhoto, this.data.msg.isShowPop, idCardFront, bankcardflag, '查看状态')

        if (this.data.msg.isNeedIdcardPhoto == 1 && this.data.msg.isShowPop == 1 && !idCardFront) {
            wx.navigateTo({
                url: `/pages/bank-id-card/bank-id-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
            })
            return
        }
        if (this.data.msg.isShowPop) {
            await app.alert('应劳务公司要求，需要您填写完银行卡号码。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
            })
            return
        }
        // b端勾选了开户行但是客户没有开户行信息
        if (this.data.isCollectOpenBankName === '1' && !user.hasOpenBankInfo) {
            await app.alert('应劳务公司要求，需要您填写完银行开户行信息。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
            })
            return
        }
        // b端勾选了开户城市但是客户没有开户城市
        if (this.data.isCollectOpenBankCity === '1' && !user.hasOpenBankCity) {
            await app.alert('应劳务公司要求，需要您填写完开户行城市信息。')
            await wx.navigateTo({
                url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
            })
            return
        }
        if (this.data.msg.isNeedIdcardPhoto === 1 && !user.hasCardPhoto) {
            await app.alert('未上传身份证照片，请在上传后在进行领取。')
            wx.navigateTo({
                url: '/pages/card-info/card-info'
            })
            return
        }
        // if (this.data.isshowCollectOpenBankAddress === 1) {
        //     await app.alert(`应劳务公司要求，需要您填写完银行卡号码和银行卡开户行。`)
        //     await wx.navigateTo({
        //         url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectOpenBankName=${this.data.isCollectOpenBankName}`,
        //     })
        //     return
        // }
        const isSalary = wx.getStorageSync('isSalary')
        // 上报统计45岁点击提现到银行卡 次数
        if (!isSalary) {
            reportEvent('salary_card', {
                'userid': user.userId,
                'age': getCardAge(this.data.msg.idCardNo),
                'salary_channel': '银行卡'
            })
            wx.setStorageSync('isSalary', 'true')
        }
        // console.log(this.data.msg.isNeedIdcardPhoto, !!this.data.idCardFront, !user.hasCardPhoto)
        // 查询微工卡
        let result
        try {
            result = await querySalaryCard(this.data.companyId)
        } catch (err) {
            if (err) {
                openSalaryCard(this.data.companyId)
            } else {
                app.alert('劳务公司暂未开通微工卡服务')
            }
        }
        if (!result.isOpenSalaryCard) {
            app.alert('劳务公司暂未开通微工卡服务')
            return
        }
        if (this.data.contractList.length === 0) {
            this.getPaid(1)
            return
        }
        await app.alert(`应劳务公司要求，需要您签署合同后领薪，您有${this.data.contractList.length}份合同待签署。`)
        goToContract(this.data.contractList[0].flowPath, this.data.contractList[0].id)
    },



    call(e) {
        if (e.currentTarget.dataset.i) {
            wx.makePhoneCall({
                phoneNumber: e.currentTarget.dataset.i,
            })
        } else {
            wx.showToast({
                icon: 'none',
                title: '暂无驻场手机号',
            })
        }

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        await this.getUrgentInfo()
        if (this.data.id) {
            this.getadvancedetail()
        }
    },


    async onGetWallet() {
        const res = await getadvancedetailapi({
            id: this.data.id
        })
        this.setData({
            isshowCollectOpenBankAddress: res.isCollectOpenBankAddress,
        })
        if (this.data.contractList.length === 0) {
            // 上报统计45岁点击提现到领钱 次数
            const isSalary = wx.getStorageSync('isSalary')
            if (!isSalary) {
                reportEvent('salary', {
                    'userid': user.userId,
                    'age': getCardAge(this.data.msg.idCardNo),
                    'salary_channel': '零钱'
                })
                wx.setStorageSync('isSalary', 'true')
            }
            // let bankcardflag = !!this.data.bankcard
            let idCardFront = !!this.data.idCardFront
            if (this.data.msg.isNeedIdcardPhoto == 1 && this.data.msg.isShowPop == 1 && !idCardFront) {
                wx.navigateTo({
                    url: `/pages/bank-id-card/bank-id-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
                })
                return
            }
            if (this.data.msg.isShowPop) {
                await app.alert('应劳务公司要求，需要您填写完银行卡号码。')
                await wx.navigateTo({
                    url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
                })
                return
            }
            // b端勾选了开户行但是客户没有开户行信息
            if (this.data.isCollectOpenBankName === '1' && !user.hasOpenBankInfo) {
                await app.alert('应劳务公司要求，需要您填写完银行开户行信息。')
                await wx.navigateTo({
                    url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
                })
                return
            }
            // b端勾选了开户城市但是客户没有开户城市
            if (this.data.isCollectOpenBankCity === '1' && !user.hasOpenBankCity) {
                await app.alert('应劳务公司要求，需要您填写完开户行城市信息。')
                await wx.navigateTo({
                    url: `/pages/bank-card/bank-card?id=${this.data.id}&isshowCollectOpenBankAddress=${this.data.isshowCollectOpenBankAddress}&isCollectOpenBankName=${this.data.isCollectOpenBankName}&isCollectOpenBankCity=${this.data.isCollectOpenBankCity}&from=advance`,
                })
                return
            }
            if (this.data.msg.isNeedIdCardPhoto === 1 && !user.hasCardPhoto) {
                await app.alert('未上传身份证照片，请在上传后在进行领取。')
                wx.navigateTo({
                    url: '/pages/card-info/card-info'
                })
                return
            }
            // if (this.data.isshowCollectOpenBankAddress === 1) {
            //     await app.alert(`应劳务公司要求，需要您填写完银行卡号码和银行卡开户行。`)
            //     await wx.navigateTo({
            //         url: '/pages/bank-card/bank-card?id=' + this.data.id + '&isshowCollectOpenBankAddress=' + this.data.isshowCollectOpenBankAddress,
            //     })
            //     return
            // }
            this.getPaid(0)
            return
        }
        await app.alert(`应劳务公司要求，需要您签署合同后领薪，您有${this.data.contractList.length}份合同待签署。`)
        goToContract(this.data.contractList[0].flowPath, this.data.contractList[0].id)
    },


    async getPaid(isBank) {
        // !!this.data.idCardFront
        if (this.data.msg.isNeedIdcardPhoto == 1 && !user.hasCardPhoto) {
            await confirm('未上传身份证照片，请在上传后在进行领取')
            // 身份证上传1
            wx.navigateTo({
                url: '/pages/card-info/card-info'
            })
        } else {
            anit(async () => {
                try {
                    const result = await getPaidadvance({
                        detailOrderNo: this.data.msg.detailOrderNo,
                        id: this.data.msg.recordId,
                        phone: this.data.msg.phone,
                        transferScene: isBank ? 'BANK_ACCOUNT' : 'WECHATPAY_ACCOUNT'
                    }, {
                        isToast: false
                    })
                    if (result && result.type === '转账失败') {
                        const event = await goApp('applet::/pages/job-status/job-status?title=提现失败&content=' + result.msg + '&type=warn&color=#FF7E68&id=' + this.data.companyId + '&phone=' + this.data.msg.phone + '&order=' + this.data.msg.detailOrderNo + '&payid=' + this.data.id + '&frompay=' + 'false')
                        this.channelPhone(event)
                        return 0
                    } else if (result && result.msg) {
                        const event = await goApp('applet::/pages/job-status/job-status?title=提现成功&content=' + result.msg + '&type=success&color=#04CD5A&id=' + this.data.companyId + '&order=' + this.data.msg.detailOrderNo + '&payid=' + this.data.id + '&phone=' + this.data.msg.phone + '&frompay=' + 'false')
                        this.channelPhone(event)
                        return 0
                    }
                    const event = await goApp('applet::/pages/job-status/job-status?title=提现成功&content=您已完成提现，稍后查看微信转账通知&type=success&color=#04CD5A&id=' + this.data.companyId + '&order=' + this.data.msg.detailOrderNo + '&payid=' + this.data.id + '&phone=' + this.data.msg.phone + '&frompay=' + 'false')
                    this.channelPhone(event)
                } catch (err) {
                    console.log(err, 'resultresult')
                    const event = await goApp('applet::/pages/job-status/job-status?title=提现失败&content=' + (err?.data?.msg ?? '网络错误，请稍后再试') + '&type=warn&color=#FF7E68&id=' + this.data.companyId + '&phone=' + this.data.msg.phone + '&isfalse=true' + '&frompay=' + 'false')
                    this.channelPhone(event)
                }
            }, 300)
        }
    },
    channelPhone(event) {
        event.eventChannel.emit('phone', this.data.msg?.linkmanList ?? [])
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})